#!/bin/sh

set -e

get_bitrate() {
	bitrate=$(ffprobe -v error -select_streams v:0 -show_entries stream=bit_rate -of default=noprint_wrappers=1:nokey=1 "$1")
	echo $((bitrate/1000))
}

[ -z "$1" ] && {
	echo "usage: $0 FILENAME [FILENAME ...]"
	echo "   or: $0 *.mp4"
	exit 1
}

total=0
count=0

while [ $# -gt 0 ]; do
	if [ -f "$1" ]; then
		vb=$(get_bitrate "$1")
		total=$((total+vb))
		count=$((count+1))
	else
		>&2 echo "error: $1: no such file"
		exit 1
	fi
	shift
done

avg=$((total/count))
echo "$avg kbps"
